﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using DotNetApp.Toolkit.Services;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using WinSource.Model;
using WinSource.Services;

namespace WinSource.ViewModel
{
    public class SavedArticlesViewModel : ViewModelBase
    {
        #region Fields

        private readonly DataService _dataService;
        private readonly NavigationService _navigationService;

        #endregion

        #region Constructor

        public SavedArticlesViewModel(DataService dataService, NavigationService navigationService)
        {
            if (!DesignerProperties.IsInDesignTool)
            {
                _dataService = dataService;
                _navigationService = navigationService;

                ReadCurrentArticleCommand = new RelayCommand(ReadCurrentArticle);
                DeleteAllArticlesCommand = new RelayCommand(DeleteAllArticles);

                _dataService.OnSavedArticlesChanged += DataServiceOnSavedArticlesChanged;

                Articles = new ObservableCollection<Article>(_dataService.SavedArticles);
            }
        }

        #endregion

        #region Properties

        public ObservableCollection<Article> Articles { get; set; }
        public Article CurrentArticle { get; set; }
        
        public RelayCommand ReadCurrentArticleCommand { get; private set; }
        public RelayCommand DeleteAllArticlesCommand { get; private set; }
        
        #endregion

        #region Command

        private void ReadCurrentArticle()
        {
            _dataService.ReadSavedArticle(CurrentArticle);

            _navigationService.NavigateTo(new Uri("/Views/SavedArticlePage.xaml", UriKind.Relative));
        }

        private void DeleteAllArticles()
        {
            _dataService.DeleteAllSavedArticles();
            Articles.Clear();

            _navigationService.GoBack();
        }

        #endregion

        #region Event Handlers

        private void DataServiceOnSavedArticlesChanged(object sender, EventArgs e)
        {
            Articles = new ObservableCollection<Article>(_dataService.SavedArticles);
        }

        #endregion
    }
}